package org.example;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {

    int getLen(ListNode head) {
        int len = 0;
        while (head != null) {
            len++;
            head = head.next;
        }
        return len;
    }

    ListNode reverse(ListNode head) {
        ListNode prev = null;
        ListNode cur = head;
        ListNode next;
        while (cur != null) {
            next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }

    public void reorderList(ListNode head) {
        int len = getLen(head);
        if (len == 0 || len == 1) {
            return;
        }
        ListNode prev = head;
        ListNode right = head;
        for (int i = 1; i <= len / 2 + len % 2; i++) {
            prev = right;
            right = right.next;
        }
        prev.next = null;

        right = reverse(right);

        ListNode left = head;
        while (right != null) {
            ListNode lnext = left.next;
            ListNode rnext = right.next;
            left.next = right;
            right.next = lnext;
            left = lnext;
            right = rnext;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}